package com.xhai.security.filter;

import com.xhai.admin.service.TokenService;
import com.xhai.common.constant.RequestConstants;
import com.xhai.common.domain.login.LoginUser;
import com.xhai.common.utils.classes.ObjectUtils;
import com.xhai.common.utils.classes.StringUtils;
import com.xhai.common.utils.encrypt.JwtUtils;
import com.xhai.security.context.AuthenticationContextHolder;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author xhai
 * @description toekn验证过滤器
 * @date 2025/6/7
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 根据请求中获取登录用户信息
        LoginUser loginUser = tokenService.getLoginUser(request);
        // 如果有token没过期，且身份认证上下文为空
        if (!ObjectUtils.isNull(loginUser) && ObjectUtils.isNull(AuthenticationContextHolder.getContext())) {
            // 验证token有效期，在有效期内则续有效期
            tokenService.refreshToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }

        filterChain.doFilter(request, response);
    }
}
